import React, {FC, useEffect, useState} from "react";
import {inject, observer} from "_mobx-react@6.3.1@mobx-react";
import {Col, Form, Input, message, Modal, Popconfirm, Row, Select, Table} from "antd";
import api from "../../../api";
import {reg, roleList} from "../../../utils";
import BreadcrumbPath from "../../../components/BreadcrumbPath";

const UserList: FC<any> = ({MobxData}) => {
    const {userList, getUserList, changeUserList} = MobxData;
    const [dataSource, setDataSource] = useState<Array<any>>([]);
    //班级信息
    const {classList, getClassList, changeClassList} = MobxData;
    const {userInfo} = MobxData;
    // 对话框是否可见
    const [isModalVisible, setIsModalVisible] = useState(false);

    const [form] = Form.useForm();
    const [role, setRole] = React.useState(0);

    // 表头内容
    const columns = [
        {
            title: '用户名',
            dataIndex: 'username',
            key: 'username',
            width: 'auto',
        },
        {
            title: '手机号码',
            dataIndex: 'phone',
            key: 'phone',
            width: 'auto',
        },
        {
            title: '密码',
            dataIndex: 'password',
            key: 'password',
            width: 'auto',
        },
        {
            title: '角色',
            dataIndex: 'role',
            key: 'role',
            width: 'auto'
        },
        {
            title: '班级',
            dataIndex: 'classname',
            key: 'classname',
            width: 'auto',
            render: (text: any, record: any) => {
                if (record.role != "学员") {
                    return '老师或管理员没有班级';
                } else {
                    return text ? text : "还未分配班级";
                }
            }
        },
        {
            title: '操作',
            key: 'action',
            width: '200px',
            render: (text: any, record: any, index: any) => {
                return (
                    <div style={{color: "#409eff"}}>
                    <span style={{margin: "0 10px", cursor: "pointer"}} onClick={() => {
                        form.setFieldsValue(record)
                        setIsModalVisible(true);
                    }}>修改</span>
                        <Popconfirm
                            title="确定要删除吗?"
                            onConfirm={() => {
                                // console.log("删除");
                                // 删除班级
                                api.delUser({id: record.key}).then(res => {
                                    message.success(res.msg);
                                }).catch(err => {
                                    message.error(err.msg);
                                })
                                // 更新数据
                                getUserList();
                            }}
                            okText="确定"
                            cancelText="取消"
                        >
                            <span style={{margin: "0 10px", cursor: "pointer"}}>删除</span>
                        </Popconfirm>
                    </div>
                )
            }
        }
    ];
    if (userInfo.role < 2) {
        columns.pop();
    }

    useEffect(() => {
        getUserList();
        getClassList();
    }, [])
    useEffect(() => {
        // 拼装表格数据
        setDataSource(userList.map((item: any) => ({
            key: item._id,
            username: item.username,
            phone: item.phone,
            password: item.password,
            role: roleList.find(obj => obj.id === item.role)!.name,
            classname: item.classname,
        })))
    }, [userList])

    const handleOk = () => {
        // 验证表单
        form.validateFields().then(values => {
            values.id = form.getFieldValue("key");
            // console.log(values);
            // 更新用户信息
            api.upUser(values).then(res => {
                message.success(res.msg);
                // 更新数据
            }).catch(err => {
                message.error(err.msg);
            })

            // 更新数据
            getUserList()
            // 关闭对话框
            setIsModalVisible(false)
        }).catch(err => {
        })
    }

    return (
        <div>
            {/*<h1>用户列表</h1>*/}
            <BreadcrumbPath/>
            <Input type="search" placeholder="输入您想要搜索的关键词" onChange={(e) => {
                const searchContent = e.target.value;
                setDataSource(
                    userList
                        .map((item: any) => ({
                            key: item._id,
                            username: item.username,
                            phone: item.phone,
                            password: item.password,
                            role: roleList.find(obj => obj.id === item.role)!.name,
                            classname: item.classname,
                        }))
                        .filter((item: any) => {
                            if (searchContent === '' || item.username.includes(searchContent) || item.phone.includes(searchContent) || item.password.includes(searchContent) || item.role.includes(searchContent) || item.classname.includes(searchContent)) {
                                return true
                            }
                        }))
            }}/>

            <Table dataSource={dataSource} columns={columns} sticky
                   pagination={{
                       pageSize: 8,
                       hideOnSinglePage: true,
                       responsive: true,
                       position: ["bottomCenter"],
                       showQuickJumper: true
                   }}/>
            <Modal title="修改用户信息" okText="提交" cancelText="取消" visible={isModalVisible}
                   onOk={handleOk}
                   onCancel={() => {
                       setIsModalVisible(false)
                   }}>
                <Form
                    name="basic"
                    form={form}
                    layout='vertical'
                >
                    <Form.Item
                        label="用户名"
                        name="username"
                        rules={[{required: true, message: '用户名不能为空!'}]}
                    >
                        <Input placeholder="请输入用户名"/>
                    </Form.Item>
                    <Form.Item
                        label="手机号码"
                        name="phone"
                        rules={[{required: true, message: '手机号码不能为空!'}, {pattern: reg.phone, message: '请输入正确的手机号码!'}]}
                    >
                        <Input placeholder="请输入手机号码"/>
                    </Form.Item>
                    <Form.Item
                        label="密码"
                        name="password"
                        rules={[
                            {required: true, message: '密码不能为空!'},
                            {pattern: reg.password, message: '请输入6-16的密码包含数字、字母、字符中的两种!'}
                        ]}
                    >
                        <Input placeholder="请输入密码"/>
                    </Form.Item>
                    <Row>
                        <Col span={12}>
                            <Form.Item
                                label="角色"
                                name="role"
                                rules={[{required: true, message: '用户角色不能为空!'}]}
                            >
                                <Select style={{width: "100%"}} onChange={(value) => {
                                    setRole(value)
                                }}>
                                    {
                                        roleList.map((item: any) => {
                                            return <Select.Option value={item.id}
                                                                  key={item.id}>{item.name}</Select.Option>
                                        })
                                    }
                                </Select>
                            </Form.Item>
                        </Col>
                        {
                            role < 1 && (
                                <Col span={12}>
                                    <Form.Item
                                        label="班级"
                                        name="classname"
                                        rules={[{required: true, message: '班级名称不能为空!'}]}
                                    >
                                        <Select style={{width: "100%"}} onChange={() => {
                                        }}>
                                            {
                                                classList.map((item: any) => {
                                                    return <Select.Option value={item.name}
                                                                          key={item._id}>{item.name}</Select.Option>
                                                })
                                            }
                                        </Select>
                                    </Form.Item>
                                </Col>
                            )
                        }
                    </Row>
                </Form>
            </Modal>
        </div>
    )
}
export default inject('MobxData')(observer(UserList));